package com.qfedu.web.servlet;

import com.alibaba.fastjson.JSON;
import com.qfedu.pojo.Address;
import com.qfedu.pojo.Cart;
import com.qfedu.pojo.Order;
import com.qfedu.pojo.User;
import com.qfedu.service.AddressService;
import com.qfedu.service.CartService;
import com.qfedu.service.OrderService;
import com.qfedu.service.impl.AddressServiceImpl;
import com.qfedu.service.impl.CartServiceImpl;
import com.qfedu.service.impl.OrderServiceImpl;
import com.qfedu.web.common.BaseServlet;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 创建者: QF-SUN
 * 创建时间: 2023/4/6 9:16
 * 描述:
 */
@WebServlet("/orderservlet")
public class OrderServlet extends BaseServlet {

    OrderService orderService = new OrderServiceImpl();

    CartService cartService = new CartServiceImpl();
    AddressService addressService = new AddressServiceImpl();

    public String addOrder(HttpServletRequest request, HttpServletResponse response) {

        //1. 获取用户
        Object obj = request.getSession().getAttribute("user");
        if(obj == null){
            return "redirect:/login.jsp";
        }
        String addrId = request.getParameter("aid");

        User user = (User) obj;


        Order  order = orderService.addOrder(user.getId(), Integer.parseInt(addrId));

        request.setAttribute("order", order);

        return "forward:/orderSuccess.jsp";
    }

    /**
     * 展示预览订单页面
     * 1. 查询该用户的购物车
     * 2. 查询该用户地址列表
     * @param request
     * @param response
     * @return
     */
    public String getOrderView(HttpServletRequest request, HttpServletResponse response) {
        //1. 获取用户
        Object obj = request.getSession().getAttribute("user");
        if(obj == null){
            return "redirect:/login.jsp";
        }

        User user = (User) obj;

        //查询该用户的购物车
        List<Cart> carts = cartService.selectCart(user.getId());

        //查询该用户地址列表
        List<Address> addressList  = addressService.selectAddresses(user.getId());
        //把数据存储到请求域
        request.setAttribute("carts", carts);
        request.setAttribute("addList", addressList);

        return "forward:/order.jsp";

    }
}
